<?php

namespace app\controllers;

use app\librarys\BaseController;
use app\librarys\FileService;
use app\librarys\Tools;
use app\models\Credit;
use app\models\Permission;
use app\models\Recharge;
use app\models\Invocie;
use app\models\Institution;
use app\models\Manager;
use yii\data\Pagination;
use yii\helpers\VarDumper;

class FinanceController extends BaseController
{
    /**
     * 授信记录列表
     * @return string
     * @throws \Exception
     */
    public function actionCreditList()
    {
        $currentInstitutionCode = Manager::getCurrentManager()['institution_code'];
        if ($currentInstitutionCode == '0') {
            $institutionName = '----全部机构----';
        } else {
            $institutionName = Manager::getCurrentManager()['institution_name'];
        }

        $institutionCode = \Yii::$app->request->get('institution_code', '');
        if ($institutionCode == '') {
            $institutionCode = Manager::getCurrentManager()['institution_code'];
        }

        $creditStatus = \Yii::$app->request->get('credit_status', '0');

        if (!Permission::hasInstitutionPermission($institutionCode)) {
            throw new \Exception('无权限访问此数据!');
        }

        $pageSize = 10;

        if ($institutionCode == Manager::getCurrentManager()['institution_code'] && $currentInstitutionCode != '0') {
            $totalCount = Credit::getCountWithChildren($institutionCode, $creditStatus);
        } else {
            $totalCount = Credit::getCount($institutionCode, $creditStatus);
        }
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $totalCount,
        ]);

        if ($institutionCode == Manager::getCurrentManager()['institution_code'] && $currentInstitutionCode != '0') {
            $items = Credit::getListWithChildren($pagination->offset, $pagination->limit, $institutionCode, $creditStatus);
        } else {
            $items = Credit::getList($pagination->offset, $pagination->limit, $institutionCode, $creditStatus);
        }

        return $this->render('credit-list',
            ['items' => $items,
                'pagination' => $pagination,
                'manager_institution_code' => $currentInstitutionCode,
                'current_institution_code' => $institutionCode,
                'current_institution_name' => $institutionName,
                'current_credit_status' => $creditStatus]);
    }

    /**
     * 授信记录详情
     * @return string
     */
    public function actionCreditDetailPartview()
    {
        $creditId = \Yii::$app->request->post('credit_id');
        $item = Credit::getDetail($creditId);

        return $this->renderPartial('credit-detail-partview', ['item' => $item]);
    }

    /**
     * 新增授信记录
     * @return string
     */
    public function actionAddCreditHandler()
    {
        $credit = \Yii::$app->request->post();

        $result = Credit::add($credit);
        if ($result > 0) {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '创建失败');
        }
    }

    /**
     * 授信记录审核
     * @return string
     */
    public function actionApproveCreditHandler()
    {
        $data = \Yii::$app->request->post();

        $result = Credit::approve($data);
        if ($result == 0) {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '审核失败');
        }
    }

    /**
     * 充值记录列表
     * @return string
     * @throws \Exception
     */
    public function actionRechargeList()
    {
        $currentInstitutionCode = Manager::getCurrentManager()['institution_code'];
        if ($currentInstitutionCode == '0') {
            $institutionName = '----全部机构----';
        } else {
            $institutionName = Manager::getCurrentManager()['institution_name'];
        }

        $current_institution_name = '';
        $institutionCode = \Yii::$app->request->get('institution_code', '');
        if ($institutionCode == '') {
            $institutionCode = Manager::getCurrentManager()['institution_code'];
        }
        $current_institution_name = Institution::getInstitutionByCode($institutionCode)['name'];


        $rechargeStatus = \Yii::$app->request->get('recharge_status', '0');
        $startTime = \Yii::$app->request->get('startTime');
        $endTime = \Yii::$app->request->get('endTime');


        if (!Permission::hasInstitutionPermission($institutionCode)) {
            throw new \Exception('无权限访问此数据!');
        }

        $pageSize = 10;

        if ($institutionCode == Manager::getCurrentManager()['institution_code'] && $currentInstitutionCode != '0') {
            $totalCount = Recharge::getCountWithChildren($institutionCode, $rechargeStatus, $startTime, $endTime);
        } else {
            $totalCount = Recharge::getCount($institutionCode, $rechargeStatus, $startTime, $endTime);
        }



        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $totalCount,
        ]);

        if ($institutionCode == Manager::getCurrentManager()['institution_code'] && $currentInstitutionCode != '0') {
            $items = Recharge::getListWithChildren($pagination->offset, $pagination->limit, $institutionCode, $rechargeStatus, $startTime, $endTime);
        } else {
            $items = Recharge::getList($pagination->offset, $pagination->limit, $institutionCode, $rechargeStatus, $startTime, $endTime);
        }


        return $this->render('recharge-list',
            [
                'items' => $items,
                'pagination' => $pagination,
                'current_institution_code' => $currentInstitutionCode,
                'current_institution_name' =>$current_institution_name,
                'current_credit_status' => $rechargeStatus,
                'startTime' => $startTime,
                'endTime' => $endTime
            ]);
    }

    /**
     * 新增充值记录
     * @return string
     */
    public function actionAddRechargeHandler()
    {
        $request = \Yii::$app->request;
        $institution_code = $request->post('inputInstitution_name');
        $amount = $request->post('inputRechargeAmount');
        $mode = $request->post('recharge_mode');
        $payment_name = $request->post('inputPaymentName');
        $receivable_name = $request->post('inputReceivableName');
        $receivable_bank = $request->post('inputReceivableBank');
        $receivable_account = $request->post('inputReceivableAccount');
        $remark = $request->post('inputRemark');

        $file_list = [];
        //读取上传的图片文件
        if (isset($_FILES['file'])) {
            for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
                if ($_FILES['file']['error'][$i] == 0) {
                    $fileName = Tools::uuid() . '.' . pathinfo($_FILES['file']["name"][$i])['extension'];
                    $filePath = $_FILES['file']["tmp_name"][$i];
                    $file_url = FileService::uploadImage($filePath, $fileName);
                    array_push($file_list,
                        [
                            'url' => $file_url,
                            'name' => $_FILES['file']['name'][$i]
                        ]);
                }
            }
        }
        $currentInstitutionCode = Manager::getCurrentManager()['institution_code'];
        $result = Recharge::add($institution_code, $amount, $mode, $payment_name, $receivable_name, $receivable_bank, $receivable_account, $remark, $file_list,$currentInstitutionCode);
        return $this->renderJson($result, $result ? 0 : 1, '');
    }

    /**
     * 充值记录详情
     * @return string
     */
    public function actionRechargeDetailPartview()
    {
        $rechargeId = \Yii::$app->request->post('recharge_id');
        $item = Recharge::getDetail($rechargeId);
        $item['attachments'] = Recharge::getAttachment($rechargeId);

        return $this->renderPartial('recharge-detail-partview', ['item' => $item]);
    }

    /**
     * 充值记录审核
     * @return string
     */
    public function actionApproveRechargeHandler()
    {
        $data = \Yii::$app->request->post();

        $result = Recharge::approve($data);
        if ($result == 0) {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '审核失败');
        }
    }

    /**
     * 发票记录列表
     * @return string
     */
    public function actionInvoiceList()
    {
        $pageSize = 10;

        //当前用户的机构-----------------------------------------------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        //$institution ='I1';
        //---------------------------------------------------------------

        $request = \Yii::$app->request;
        $start = $request->get("page");

        $status = $request->get("status");
        $filter = $request->get("filter");
        $startTime = $request->get("startTime");
        $endTime = $request->get("endTime");

        if ($start == '') {
            $start = '0';
        } else {
            $start = ($start - 1) * $pageSize;
        }
        if ($status == '') {
            $status = '99';
        }
        if ($startTime == '') {
            $startTime = '0';
        }
        if ($endTime == '') {
            $endTime = '0';
        }
        if ($filter == '') {
            $filter = '0';
        }

        $totalCount = Invocie::getInvoiceListTotal($startTime, $endTime, $status, $filter, $institution);

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $totalCount,
        ]);

        $items = Invocie::getInvoiceList($start, $pageSize, $startTime, $endTime, $status, $filter, $institution);

        //下拉列表相关数据
        $selectList = Institution::getInstitutionSelectList(0, $institution);


        return $this->render('invoice-list',
            ['items' => $items,
                'pagination' => $pagination,
                'status' => $status,
                'filter' => $filter,
                'startTime' => $startTime,
                'endTime' => $endTime,
                'institution' => $institution,
                'institutionList' => $selectList['institutionList']]);
    }

    /**
     * 发票申请详情
     * @return string
     */
    public function actionAddAuditInvoiceHandler()
    {
        //当前用户的机构-----------------------------------------------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        //$institution ='I1';
        //---------------------------------------------------------------

        $request = \Yii::$app->request;
        $invId = $request->post("id");
        $invName = $request->post("invHead");
        $invIns = $request->post("invIns");

        if ($invId == '0') {
            if ($institution == '0') {
                $result['invoice_head'] = '';
                $result['invoiced'] = 0;
                $result['recharged'] = 0;
            } else {
                $result['invoice_head'] = $invName;
                $result['invoiced'] = Invocie::getInvoiced($invIns);
                $result['recharged'] = Recharge::getRecharged($invIns);
            }
            $result['id'] = 0;
            $result['institution_code'] = $institution;
            $result['fp_date'] = '';
            $result['invoice_type'] = 0;
            $result['category_name'] = '技术服务费';
            $result['unit'] = '';
            $result['pcount'] = 1;
            $result['p_money'] = '';
            $result['remark'] = '';
            $result['audit_remark'] = '';
            $result['applay_user'] = '';
            $result['applay_time'] = '';
            $result['audit_status'] = 0;
            $result['audit_user'] = '';
            $result['audit_time'] = '';
            $result['applay_name'] = '';
            $result['audit_name'] = '';
        } else {
            $result = Invocie::getInvoiceDetail($invId);
            $result['invoiced'] = Invocie::getInvoiced($result['institution_code']);
            $result['recharged'] = Recharge::getRecharged($result['institution_code']);
        }

        return $this->renderJson(['result' => $result, 'institution' => $institution], 0, 0);
    }

    /**
     * 申请发票选择机构
     * @return string
     */
    public function actionUninvoiceHandler()
    {
        $request = \Yii::$app->request;
        $invIns = $request->post("invIns");
        $result['invoiced'] = Invocie::getInvoiced($invIns);
        $result['recharged'] = Recharge::getRecharged($invIns);
        return $this->renderJson($result, 0, 0);
    }

    /**
     * 发票申请保存确认
     * @return string
     */
    public function actionAddConfirmHandler()
    {
        //-------当前用户-------------------
        $current_console_user = Manager::getCurrentManager();
        $userId = $current_console_user['id'];
        //-----------------------------
        $request = \Yii::$app->request;
        $institution_code = $request->post("applyIns");
        $invoice_head = $request->post("invHead");
        $fp_date = $request->post("fp_date");
        $invoice_type = $request->post("selectTYPE");
        $category_name = $request->post("category_name");
        $unit = $request->post("unit");
        $pcount = $request->post("pcount");
        $p_money = $request->post("p_money");
        $remark = $request->post("remark");
        $applay_user = $userId;

        $result = Invocie::saveInvoice($institution_code, $invoice_head, $fp_date, $invoice_type, $category_name, $unit, $pcount, $p_money, $remark, $applay_user);
        return $this->renderJson(0, $result, 0);
    }

    /**
     * 发票申请审核
     * @return string
     */
    public function actionAuditConfirmHandler()
    {
        //-------当前用户-------------------
        $current_console_user = Manager::getCurrentManager();
        $userId = $current_console_user['id'];
        //-----------------------------
        $request = \Yii::$app->request;
        $invId = $request->post("id");
        $flag = $request->post("flag");
        $auditRemark = $request->post("auditRemark");

        $result = Invocie::setInvoiceStatus($invId, $flag, $auditRemark, $userId);
        return $this->renderJson(0, $result, 0);
    }

    /**
     * 发票申请删除
     * @return string
     */
    public function actionDelConfirmHandler()
    {
        //-------当前用户-------------------
        $current_console_user = Manager::getCurrentManager();
        $userId = $current_console_user['id'];
        //-----------------------------
        $request = \Yii::$app->request;
        $invId = $request->post("id");
        $flag = $request->post("flag");
        $auditRemark = $request->post("auditRemark");

        $result = Invocie::setInvoiceStatus($invId, $flag, $auditRemark, $userId);
        return $this->renderJson(0, $result, 0);
    }
}